package com.tcl.hystrix.config;

import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixObservableCommand;
import com.tcl.api.response.UserResponse;
import com.tcl.hystrix.feign.UserServiceFeignClient02;
import rx.Observable;
import rx.schedulers.Schedulers;

/**
 * @Author liuf
 * @Date 2020/12/17 17:08
 * @Description
 */
public class ObservableFeignHystrix extends HystrixObservableCommand<UserResponse> {
    private UserServiceFeignClient02 userServiceFeignClient02;

    private Integer userId;

    public ObservableFeignHystrix(UserServiceFeignClient02 userServiceFeignClient02, Integer userId) {
        // 调用父类构造方法
        super(HystrixCommandGroupKey.Factory.asKey("userServiceFeignClient02"));
        this.userServiceFeignClient02 = userServiceFeignClient02;
        this.userId = userId;
    }

    @Override
    protected Observable<UserResponse> construct() {

        /*
         * Observable有三个关键的事件方法，分别为onNext，onCompleted，onError
         */
        return Observable.create((Observable.OnSubscribe<UserResponse>) observer -> {
            try {// 写业务逻辑，注意try-catch
                if (!observer.isUnsubscribed()) {
                    UserResponse userResponse = userServiceFeignClient02.get(userId);
                    observer.onNext(userResponse);
                    observer.onCompleted();
                }
            } catch (Exception e) {
                observer.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    @Override
    protected Observable<UserResponse> resumeWithFallback() {
        return Observable.create(subscriber -> {
            if (!subscriber.isUnsubscribed()) {
                UserResponse userResponse = new UserResponse();
                userResponse.setId(1);
                userResponse.setName("服务降级");
                subscriber.onNext(userResponse);
                subscriber.onCompleted();
            }
        });
    }
}
